import { Node, AudioSource, AudioClip, resources, director } from 'cc';
import { ResManager } from './ResManager';

export class AudioMgr {
    private static _instance: AudioMgr;
    volume:number=1.0
    public static get instance(): AudioMgr {
        if (this._instance == null) {
            this._instance = new AudioMgr();
        }
        return this._instance;
    }
    private _audioSource: AudioSource;
    constructor() {
        //@en create a node as audioMgr
        //@zh 创建一个节点作为 audioMgr
        let audioMgr = new Node();
        audioMgr.name = '__audioMgr__';

        //@en add to the scene.
        //@zh 添加节点到场景
        director.getScene().addChild(audioMgr);

        //@en make it as a persistent node, so it won't be destroied when scene change.
        //@zh 标记为常驻节点，这样场景切换的时候就不会被销毁了
        director.addPersistRootNode(audioMgr);

        //@en add AudioSource componrnt to play audios.
        //@zh 添加 AudioSource 组件，用于播放音频。
        this._audioSource = audioMgr.addComponent(AudioSource);
    }
    public get audioSource() {
        return this._audioSource;
    }
    /**
     * @en
     * play long audio, such as the bg music
     * @zh
     * 播放长音频，比如 背景音乐
     * @param sound clip or url for the sound
     * @param volume 
     */
    play(sound:string,type:string,volume: number = 1.0,) {
        const clip=ResManager.Instance.getAudioClip(sound);
        if(type=='short'){
            this._audioSource.playOneShot(clip, volume);
            return
        }
        this._audioSource.stop();
        this._audioSource.loop=true
        this._audioSource.clip = clip;
        this._audioSource.play();
        this.audioSource.volume = volume;            
    }
    stop() {
        this._audioSource.stop();
    }
    changesound(volume:number){
        this.volume=volume
    }
    pause() {
        this._audioSource.pause();
    }
    resume(){
        this._audioSource.play();
    }
}


